package upfile

import (
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gstr"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"os"
	"strings"
	attachmentModel "myblog/app/model/module/attachment"
)

func Upfile(files ghttp.UploadFiles) ([]string, error) {
	curDir, err := os.Getwd()
	if err != nil {
		return nil, err
	}
	saveDir := curDir + g.Cfg().GetString("upfile.uppath") //文件保存路径
	names, err := files.Save(saveDir, true)
	for _, v := range names {
		filepath := saveDir + "/" + v
		file, _ := os.Open(filepath)
		defer file.Close()
		temp, _ := file.Stat()
		c, _, _ := image.DecodeConfig(file)
		var entity attachmentModel.Entity
		entity.Filename = temp.Name()
		entity.Filepath = g.Cfg().GetString("upfile.uppath") + v
		entity.Filesize = temp.Size()
		entity.Imagewidth = c.Width
		entity.Imageheight = c.Height
		entity.CreateTime = gtime.Now()
		entity.Insert()
	}
	return names, nil
}

//删除文件
func Delfile(url string) error {
	curDir, err := os.Getwd()
	if err != nil {
		return err
	}
	err = os.Remove(curDir + "/public/" + url)
	index := strings.LastIndex(url, "/")
	filename := gstr.SubStr(url, index+1)
	if err != nil {
		return err
	}
	db, _ := gdb.Instance()
	model := db.Model("t_attachment")
	model.Delete("filename=?", filename)
	return nil
}
